<template>
  <el-dialog
    :append-to-body="true"
    v-model="visible"
    @close="resetDig(ruleFormRef)"
    title=""
    width="380"
    :close-on-click-modal="false"
  >
    <el-form
      ref="ruleFormRef"
      :model="passForm"
      :rules="passRules"
      class="register-form"
    >
      <div>
        <div class="text-2xl font-semibold text-center mb-[25px]">找回密码</div>
        <el-form-item class="flex items-center mt-[10px]" prop="mobilePhone">
          <el-input
            v-model="passForm.mobilePhone"
            class="w-[280px!important] m-auto mt-[15px]"
            type="text"
            :prefix-icon="Iphone"
            placeholder="请输入手机号码"
          />
        </el-form-item>
        <el-form-item class="flex items-center" prop="verificationCode">
          <el-input
            v-model="passForm.verificationCode"
            class="w-[145px!important] m-auto mt-[15px]"
            type="text"
            :prefix-icon="ChatDotRound"
            placeholder="请输入验证码"
          />
          <el-button
            type="primary"
            :disabled="countdown > 0"
            @click="getCaptcha"
            class="mt-[10px] mr-[35px]"
            >{{
              countdown > 0 ? `${countdown}秒后重试` : "获取验证码"
            }}</el-button
          >
        </el-form-item>
        <el-form-item class="flex items-center" prop="personPwd">
          <el-input
            v-model="passForm.personPwd"
            class="w-[280px!important] m-auto mt-[15px]"
            type="password"
            :prefix-icon="Lock"
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item class="flex items-center" prop="confirmPassword">
          <el-input
            v-model="passForm.confirmPassword"
            class="w-[280px!important] m-auto mt-[15px]"
            type="password"
            :prefix-icon="Lock"
            placeholder="请确认密码"
          />
        </el-form-item>
        <div class="m-auto text-center">
          <el-button
            type="primary"
            @click="retrievePassword(ruleFormRef)"
            class="w-[280px] mt-[30px]"
            >找回密码</el-button
          >
          <div
            class="w-[300px] text-xs ml-[12px] mt-[10px] text-right cursor-pointer"
            @click="toggleRegister"
          >
            已有账号,<span style="color: #f07700">去登录 </span
            ><img
              class="inline-flex"
              style="margin-top: -3px"
              src="../../assets/images/qu_jian_tou.png"
            />
          </div>
        </div>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, reactive } from "vue";
import {
  UserFilled,
  Lock,
  Iphone,
  ChatDotRound,
} from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { updatePwdByCode, sendCode } from "@renderer/api/login";
import { encryptExternalUsers } from "@renderer/utils/jsencrypt";
const showLogin = ref(false);
const emit = defineEmits(["close-dialog", "update:reset", "goLogin"]);
const countdown = ref(0);
const props = defineProps({
  reset: {
    type: Boolean,
    default: false,
  },
});
const ruleFormRef = ref<FormInstance>();
interface RuleForm {
  personPwd: string;
  confirmPassword: string;
  mobilePhone: string;
  verificationCode: string;
}
// 初始化
const passForm = reactive<RuleForm>({
  personPwd: "",
  confirmPassword: "",
  mobilePhone: "",
  verificationCode: "",
});
// 再次输入密码确认
const equalToPassword = (rule, value, callback) => {
  if (passForm.personPwd !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

// 表单校验
const passRules = reactive<FormRules<RuleForm>>({
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入您的密码" },
    { required: true, validator: equalToPassword, trigger: "blur" },
  ],
  verificationCode: [
    { required: true, trigger: "blur", message: "请输入验证码" },
  ],
  mobilePhone: [
    { required: true, trigger: "blur", message: "请输入手机号" },
    {
      pattern: /^1[3|4|5|7|8|9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  personPwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { required: true, trigger: "blur" },
    {
      min: 8,
      max: 16,
      message: "密码长度为8-16个字符，必须包含大小写字母、数字、符号",
      trigger: "blur",
    },
    {
      min: 8,
      max: 16,
      pattern: /^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$/g,
      message: "密码长度为8-16个字符，必须包含大小写字母、数字、符号",
      trigger: "blur",
    }, //密码必须是8位以上、必须含有字母、数字、特殊符号
  ],
});

const toggleRegister = () => {
  showLogin.value = true;
  emit("goLogin");
};
const retrievePassword = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const password = encryptExternalUsers(passForm.personPwd);
      updatePwdByCode(
        passForm.mobilePhone,
        passForm.verificationCode,
        password
      ).then((response: any) => {
        if (response.code === 200) {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          visible.value = false;
          showLogin.value = false;
        } else {
          ElMessage.error(response.msg);
        }
      });
    }
  });
};

let visible = computed({
  get() {
    return props.reset;
  },
  set(value: boolean) {
    emit("update:reset", value);
  },
});

const getCaptcha = async () => {
  if (passForm.mobilePhone) {
    //获取验证码
    sendCode(passForm.mobilePhone)
      .then((res) => {})
      .catch((e) => {
        clearInterval(countdown.value);
      });
    // 设置倒计时
    countdown.value = 60; // 假设倒计时60秒
    const intervalId = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(intervalId);
      }
    }, 1000);
  } else {
    ElMessage.error("请先输入手机号码");
  }
};
// 弹窗关闭
const resetDig = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  countdown.value = 0;
};
</script>

<style scoped lang="scss">
:deep(.el-input__wrapper) {
  background: #373333 !important;
  box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color))
    inset;
}
//获取验证码颜色修改
.el-button.is-disabled,
.el-button.is-disabled:hover {
  background-color: #589bdf;
  background-image: none;
  border-color: #4f9ae7;
  color: var(--el-button-disabled-text-color);
  cursor: not-allowed;
}
.el-checkbox:last-of-type {
  margin-right: 68px;
}

.el-button.is-disabled,
.el-button.is-disabled:hover {
  background-color: #589bdf;
  background-image: none;
  border-color: #4f9ae7;
  color: var(--el-button-disabled-text-color);
  cursor: not-allowed;
}

:deep(.el-form-item__error) {
  left: 36px;
  padding-top: 5px;
}
</style>
